package com.splic.product.service.impl.thirdRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.splic.common.utils.DateUtils;
import com.splic.product.dto.WeatherRequestDto;
import com.splic.product.service.ThirdRequestDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ==========================
 * 开发：singe
 * 创建时间：2022-02-26 15:27
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Service
@Slf4j
public class WeatherRequestServiceImpl implements ThirdRequestDataService {

    private final String weatherUrl = "http://flash.weather.com.cn/wmaps/xml/";
    private final String weatherPrefix = ".xml";


    private final String gaodeWeatherKey = "5960001af604a5995b1b556c2ab125ee";
    private final String gaodeWeatherUrl = "https://restapi.amap.com/v3/weather/weatherInfo?city=areaCode&key=" + gaodeWeatherKey;


    private final String baiduWeatherKey = "87b2d685bef615f9992b28b76a8610fd";
    private final String baiduWeatherUrl = "https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}";


    @Autowired
    private RestTemplate restTemplate;

    @Override
    public WeatherRequestDto requestThirdData() {
        List<WeatherRequestDto.WeatherRequest> weatherList = Lists.newArrayList();
        org.json.JSONArray provinceArray = requestXml("china");
        if (provinceArray != null && provinceArray.length() > 0) {
            for (Object province : provinceArray) {
                JSONObject provinceObject = JSONObject.parseObject(province.toString());
                org.json.JSONArray cityArray = requestXml(provinceObject.getString("pyName"));
                if (cityArray != null && cityArray.length() > 0) {
                    for (Object city : cityArray) {
                        JSONObject countyObject = JSONObject.parseObject(city.toString());
                        org.json.JSONArray countyArray = requestXml(countyObject.getString("pyName"));
                        if (countyArray != null && countyArray.length() > 0) {
                            for (Object county : countyArray) {
                                JSONObject countyJsonObject = JSONObject.parseObject(county.toString());
                                WeatherRequestDto.WeatherRequest weathers = new WeatherRequestDto.WeatherRequest();
                                weathers.setWeatherCityId(countyJsonObject.getString("url"));
                                weathers.setWea(countyJsonObject.getString("stateDetailed"));
                                weathers.setTem(countyJsonObject.getString("temNow"));
                                weathers.setTem1(countyJsonObject.getString("tem2"));
                                weathers.setTem2(countyJsonObject.getString("tem1"));
                                weathers.setWinSpeed(countyJsonObject.getString("windPower"));
                                weathers.setWin(countyJsonObject.getString("windDir"));
                                weathers.setAir(countyJsonObject.getString("air"));
                                weatherList.add(weathers);
                            }
                        }
                    }
                }
            }
        }

        WeatherRequestDto dto = new WeatherRequestDto();
        dto.setWeathersList(weatherList);
        return dto;
    }

    private org.json.JSONArray requestXml(String prefixName) {
        try {
            String xmlBody = restTemplate.getForObject(weatherUrl + prefixName + weatherPrefix, String.class);
            org.json.JSONArray array = XML.toJSONObject(xmlBody).getJSONObject(prefixName).getJSONArray("city");
            return array;
        } catch (Exception e) {
            log.error(":{}", e.getMessage());
            return null;
        }
    }

    public List<WeatherRequestDto.WeatherRequest> requestThirdTodayData(String areaCode) {

        List<WeatherRequestDto.WeatherRequest> resultList = Lists.newArrayList();
        obtainTodayWeather(resultList, areaCode);
        return resultList;
    }

    public List<WeatherRequestDto.WeatherRequest> requestThirdTomorrowData(String areaCode) {

        List<WeatherRequestDto.WeatherRequest> resultList = Lists.newArrayList();
        obtainTomorrowWeather(resultList, areaCode);
        return resultList;
    }

//    public void obtainTodayWeather(List<WeatherRequestDto.WeatherRequest> resultList,String areaCode){
//        JSONObject result = restTemplate.getForObject(gaodeWeatherUrl.replace("areaCode",areaCode)+"&extensions=base",JSONObject.class);
//        if (result == null || result.getIntValue("status") != 1) {
//            log.error("获取地址位置失败");
//            return;
//        }
//        JSONArray array = result.getJSONArray("lives");
//        JSONObject json = array.getJSONObject(0);
//        WeatherRequestDto.WeatherRequest weathers = new WeatherRequestDto.WeatherRequest();
//        weathers.setWeatherCityId(json.getString("adcode"));
//        weathers.setWea(json.getString("weather"));
//        weathers.setTem(json.getString("temperature"));
//        weathers.setWinSpeed(json.getString("windpower"));
//        weathers.setWin(json.getString("winddirection"));
//        weathers.setHumidity(json.getString("humidity"));
//        weathers.setDate(new Date());
//        resultList.add(weathers);
//    }

    public void obtainTodayWeather(List<WeatherRequestDto.WeatherRequest> resultList, String areaCode) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>();
        map.put("district_id", areaCode);
        map.put("data_type", "all");
        map.put("ak", baiduWeatherKey);
        String res = restTemplate.getForObject(
                baiduWeatherUrl,
                String.class,
                map);
        JSONObject result = JSONObject.parseObject(res);
        if (result == null || result.getIntValue("status") != 0) {
            log.error("获取地址位置失败");
            return;
        }
        JSONObject jsonResult = result.getJSONObject("result");
        JSONObject now = jsonResult.getJSONObject("now");
        JSONObject location = jsonResult.getJSONObject("location");
        WeatherRequestDto.WeatherRequest weathers = new WeatherRequestDto.WeatherRequest();
        weathers.setWeatherCityId(location.getString("id"));
        weathers.setWea(now.getString("text"));
        weathers.setTem(now.getString("temp"));
        weathers.setWinSpeed(now.getString("wind_class"));
        weathers.setWin(now.getString("wind_dir"));
        weathers.setAir(now.getString("aqi"));
        weathers.setDate(new Date());
        resultList.add(weathers);
    }


//    public void obtainTomorrowWeather(List<WeatherRequestDto.WeatherRequest> resultList,String areaCode){
//        JSONObject result = restTemplate.getForObject(gaodeWeatherUrl.replace("areaCode",areaCode)+"&extensions=all",JSONObject.class);
//        if (result == null || result.getIntValue("status") != 1) {
//            log.error("获取地址位置失败");
//            return;
//        }
//        JSONArray forArray = result.getJSONArray("forecasts");
//        if(CollectionUtils.isEmpty(forArray)){
//            return;
//        }
//        JSONObject jsonObject = forArray.getJSONObject(0);
//        JSONArray castsJsonArray = jsonObject.getJSONArray("casts");
//        if(CollectionUtils.isEmpty(castsJsonArray)){
//            return;
//        }
//        Date currentDate = new Date();
//        for(Object obj:castsJsonArray){
//            Map map = (Map)obj;
//            Date date = DateUtils.parseDate(map.get("date")!=null?map.get("date").toString():null);
//            if (DateUtils.isSameDay(currentDate,date) || DateUtils.isSameDay(DateUtils.addDays(currentDate,1),date)){
//                WeatherRequestDto.WeatherRequest weathers = new WeatherRequestDto.WeatherRequest();
//                weathers.setDate(date);
//                weathers.setWeek(map.get("week")!=null?map.get("week").toString():"");
//                weathers.setWeatherCityId(jsonObject.getString("adcode"));
//                weathers.setWea(map.get("dayweather")!=null?map.get("dayweather").toString():"");
//                weathers.setTem1(map.get("daytemp")!=null?map.get("daytemp").toString():"");
//                weathers.setTem2(map.get("nighttemp")!=null?map.get("nighttemp").toString():"");
//                weathers.setWinSpeed(map.get("daypower")!=null?map.get("daypower").toString():"");
//                weathers.setWin(map.get("daywind")!=null?map.get("daywind").toString():"");
//                weathers.setHumidity(map.get("humidity")!=null?map.get("humidity").toString():"");
//                resultList.add(weathers);
//                //只保留两天数据
//                if(resultList.size() >=2){
//                    break;
//                }
//            }
//        }
//    }

    public void obtainTomorrowWeather(List<WeatherRequestDto.WeatherRequest> resultList, String areaCode) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>();
        map.put("district_id", areaCode);
        map.put("data_type", "all");
        map.put("ak", baiduWeatherKey);
        String res = restTemplate.getForObject(
                baiduWeatherUrl,
                String.class,
                map);
        JSONObject result = JSONObject.parseObject(res);
        if (result == null || result.getIntValue("status") != 0) {
            log.error("获取天气失败：" + result);
            return;
        }
        JSONObject jsonResult = result.getJSONObject("result");
        JSONArray forecasts = jsonResult.getJSONArray("forecasts");
        if (CollectionUtils.isEmpty(forecasts)) {
            return;
        }
        JSONObject location = jsonResult.getJSONObject("location");
        Date currentDate = new Date();
        for (Object obj : forecasts) {
            Map mapTemp = (Map) obj;
            Date date = DateUtils.parseDate(mapTemp.get("date") != null ? mapTemp.get("date").toString() : null);
            if (DateUtils.isSameDay(currentDate, date) || DateUtils.isSameDay(DateUtils.addDays(currentDate, 1), date)) {
                WeatherRequestDto.WeatherRequest weathers = new WeatherRequestDto.WeatherRequest();
                weathers.setDate(date);
                weathers.setWeek(mapTemp.get("week") != null ? mapTemp.get("week").toString() : "");
                weathers.setWeatherCityId(location.getString("id"));
                weathers.setWea(mapTemp.get("text_day") != null ? mapTemp.get("text_day").toString() : "");
                weathers.setTem1(mapTemp.get("high") != null ? mapTemp.get("high").toString() : "");
                weathers.setTem2(mapTemp.get("low") != null ? mapTemp.get("low").toString() : "");
                weathers.setWinSpeed(mapTemp.get("wc_day") != null ? mapTemp.get("wc_day").toString() : "");
                weathers.setWin(mapTemp.get("wd_day") != null ? mapTemp.get("wd_day").toString() : "");
                weathers.setAir(map.get("aqi") != null ? mapTemp.get("aqi").toString() : "");
                resultList.add(weathers);
                //只保留两天数据
                if (resultList.size() >= 2) {
                    break;
                }
            }
        }
    }

}
